const {mongoose}=require("../utils/db");

//创建数据库字段

const infoSchema = mongoose.Schema({
    tokenId: { type: Number, required:true },
    // companyLogo: { type: String, required: true },
    pprice: { type: String, required: true },//required为true 表示必填选项
    pname: { type: String, required: true },
    imgUrl: { type: String, required: true },
    number: { type: String, required: true },
    pid: { type: String, required: true },

    // degree: { type: String, required: true },
    // type: { type: String, required: true },
    // experience: { type: String, required: true },
    // // description: { type: String, required: true },
    // createTime: { type: String},
    // companyLogo:{type:String},
    // allcount:{type:String}
    uid:{ type: String, required: true },
})

//创建集合
let userInfo = mongoose.model("infos",infoSchema);

//增
//data是前端通过post 或者 get 传过来的值
const add = (data)=>{
    //然后新建一个userinfo对象  entity
    const userEntity = new userInfo(data);
  
    return userEntity.save()
    .then(result=>result)
    .catch(err=>{
        console.log(err);
    })
}


//删  由mysql里的延申过来可以知道 要删除 肯定需要一个主键，根据主键删除 ，这里面的tokenId 就是主键
//删除成功 就返回被删掉的内容
const del = (tokenId)=>{
    return userInfo.deleteOne({tokenId:tokenId})
    .then(result=>result
        //删除失败的result  ==>{ n: 0, ok: 1, deletedCount: 0 }
        //删除成功的result ==>{n:1}
        //return到前面接收的时候,需要判断的是result.n 
        // console.log(result)
    )
    .catch(err=>{
        console.log(err)
    })
}

//删除后更新tokenId的方法
const updateTokenId=(tokenId)=>{
    //查询条件为 比删除的id大的数据
    let query = {tokenId:{$gt:tokenId}};
    // console.log(query)
    //让比它大的id都自减1
    let updated ={$inc:{"tokenId":-1}};
    // console.log(updated)
    //({tokenId:10},{$inc:{tokenId:-1}});
    return userInfo.updateMany(query,updated)
    .then(res=>res)
    .catch(err=>{
        console.log(err)
    })
}

//改
//query是 查询到的数据  updates 是需要改成的内容
const update = (query,updates)=>{
    console.log(query,updates);
    return userInfo.updateOne(query,updates)
    .then(result=>result).catch(
       err=>{
           console.log(err)
       }
    )
  
}


//查询
const check = (count,CurrentPage,query)=>{
   
   //如果check里面默认什么都没传的话,就返回所有的东西
   return userInfo.find(query)
   .then(result=>result)
   .catch(err=>{
       console.log(err)
   })
}

const checkAll =()=>{
    return userInfo.find().count()
   .then(result=>result)
   .catch(err=>{
       console.log(err)
   })
}

module.exports={
    add,
    del,
    update,
    check,
    updateTokenId,
    checkAll
}

